/**
 * ETF网格交易2.0系统 - 高级策略压力测试
 * 实现三个子策略：留利润、逐格加码、一网打尽
 * 遵循DRY、KISS、SOLID、YAGNI原则
 */

class GridTradingSystem2 {
    constructor() {
        this.gridData = [];
        this.priceHistory = [];
        this.profitHistory = [];
        this.charts = {};
        this.initializeCharts();
    }

    /**
     * 初始化图表
     */
    initializeCharts() {
        // 价格走势图
        const priceCtx = document.getElementById('priceChart').getContext('2d');
        this.charts.price = new Chart(priceCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '价格走势',
                    data: [],
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: '价格走势与网格交易点'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: false,
                        title: {
                            display: true,
                            text: '价格'
                        }
                    }
                }
            }
        });

        // 收益曲线图
        const profitCtx = document.getElementById('profitChart').getContext('2d');
        this.charts.profit = new Chart(profitCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '累计收益',
                    data: [],
                    borderColor: '#27ae60',
                    backgroundColor: 'rgba(39, 174, 96, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: '累计收益曲线'
                    }
                },
                scales: {
                    y: {
                        title: {
                            display: true,
                            text: '收益 (元)'
                        }
                    }
                }
            }
        });
    }

    /**
     * 2.1 留利润策略 - 生成网格数据
     */
    generateProfitRetentionGrid(params) {
        const { initialPrice, gridMode, gridSize, gridStep, totalAmount, gridCount, profitRetentionRate } = params;
        const gridData = [];
        const amountPerGrid = totalAmount / gridCount;

        for (let i = 0; i < gridCount; i++) {
            let buyPrice, sellPrice;
            
            if (gridMode === 'percentage') {
                // 百分比模式：等比数列
                buyPrice = initialPrice * Math.pow(1 - gridSize / 100, i);
                sellPrice = i === 0 ? initialPrice * (1 + gridSize / 100) : 
                           initialPrice * Math.pow(1 - gridSize / 100, i - 1);
            } else {
                // 固定步长模式：等差数列
                buyPrice = initialPrice - (gridStep * i);
                sellPrice = i === 0 ? initialPrice + gridStep : 
                           initialPrice - (gridStep * (i - 1));
            }
            
            // 计算基础收益
            const baseReturn = (sellPrice - buyPrice) * (amountPerGrid / buyPrice);
            // 计算保留的利润
            const retainedProfit = baseReturn * (profitRetentionRate / 100);
            // 实际可获得的收益
            const actualReturn = baseReturn - retainedProfit;
            const returnRate = actualReturn / (amountPerGrid / buyPrice) / buyPrice * 100;

            gridData.push({
                level: i + 1,
                buyPrice: buyPrice.toFixed(4),
                sellPrice: sellPrice.toFixed(4),
                amount: amountPerGrid.toFixed(2),
                expectedReturn: actualReturn.toFixed(2),
                retainedProfit: retainedProfit.toFixed(2),
                returnRate: returnRate.toFixed(2)
            });
        }

        return gridData;
    }

    /**
     * 2.2 逐格加码策略 - 生成网格数据
     */
    generateProgressiveBettingGrid(params) {
        const { initialPrice, gridMode, gridSize, gridStep, baseAmount, increaseRate, startFromGrid, gridCount } = params;
        const gridData = [];

        for (let i = 0; i < gridCount; i++) {
            let buyPrice, sellPrice;
            
            if (gridMode === 'percentage') {
                // 百分比模式：等比数列
                buyPrice = initialPrice * Math.pow(1 - gridSize / 100, i);
                sellPrice = i === 0 ? initialPrice * (1 + gridSize / 100) : 
                           initialPrice * Math.pow(1 - gridSize / 100, i - 1);
            } else {
                // 固定步长模式：等差数列
                buyPrice = initialPrice - (gridStep * i);
                sellPrice = i === 0 ? initialPrice + gridStep : 
                           initialPrice - (gridStep * (i - 1));
            }
            
            // 计算投入金额（逐格加码）
            let amount;
            if (i < startFromGrid - 1) {
                amount = baseAmount;
            } else {
                const increaseTimes = i - (startFromGrid - 1);
                amount = baseAmount * Math.pow(1 + increaseRate / 100, increaseTimes);
            }

            const expectedReturn = (sellPrice - buyPrice) * (amount / buyPrice);
            const returnRate = (sellPrice - buyPrice) / buyPrice * 100;

            gridData.push({
                level: i + 1,
                buyPrice: buyPrice.toFixed(4),
                sellPrice: sellPrice.toFixed(4),
                amount: amount.toFixed(2),
                expectedReturn: expectedReturn.toFixed(2),
                returnRate: returnRate.toFixed(2)
            });
        }

        return gridData;
    }

    /**
     * 2.3 一网打尽策略 - 生成多网格数据
     */
    generateMultiGridData(params) {
        const { 
            initialPrice, 
            gridMode,
            totalAmount, 
            smallGridRatio, mediumGridRatio, largeGridRatio,
            smallGridLayers, mediumGridLayers, largeGridLayers,
            smallGridSize, mediumGridSize, largeGridSize,
            smallGridStep, mediumGridStep, largeGridStep
        } = params;

        const smallGridAmount = totalAmount * (smallGridRatio / 100);
        const mediumGridAmount = totalAmount * (mediumGridRatio / 100);
        const largeGridAmount = totalAmount * (largeGridRatio / 100);

        const grids = {
            small: this.generateSingleGridWithMode(initialPrice, gridMode, smallGridSize, smallGridStep, smallGridAmount, smallGridLayers, '小网'),
            medium: this.generateSingleGridWithMode(initialPrice, gridMode, mediumGridSize, mediumGridStep, mediumGridAmount, mediumGridLayers, '中网'),
            large: this.generateSingleGridWithMode(initialPrice, gridMode, largeGridSize, largeGridStep, largeGridAmount, largeGridLayers, '大网')
        };

        return grids;
    }

    /**
     * 生成单个网格数据（支持网格模式）
     */
    generateSingleGridWithMode(initialPrice, gridMode, gridSize, gridStep, totalAmount, gridCount, gridType) {
        const gridData = [];
        const amountPerGrid = totalAmount / gridCount;

        for (let i = 0; i < gridCount; i++) {
            let buyPrice, sellPrice;
            
            if (gridMode === 'percentage') {
                // 百分比模式：等比数列
                buyPrice = initialPrice * Math.pow(1 - gridSize / 100, i);
                sellPrice = i === 0 ? initialPrice * (1 + gridSize / 100) : 
                           initialPrice * Math.pow(1 - gridSize / 100, i - 1);
            } else {
                // 固定步长模式：等差数列
                buyPrice = initialPrice - (gridStep * i);
                sellPrice = i === 0 ? initialPrice + gridStep : 
                           initialPrice - (gridStep * (i - 1));
            }

            const expectedReturn = (sellPrice - buyPrice) * (amountPerGrid / buyPrice);
            const returnRate = (sellPrice - buyPrice) / buyPrice * 100;

            gridData.push({
                level: i + 1,
                buyPrice: buyPrice.toFixed(4),
                sellPrice: sellPrice.toFixed(4),
                amount: amountPerGrid.toFixed(2),
                expectedReturn: expectedReturn.toFixed(2),
                returnRate: returnRate.toFixed(2),
                gridType: gridType
            });
        }

        return gridData;
    }

    /**
     * 生成单个网格数据（兼容旧版本）
     */
    generateSingleGrid(initialPrice, gridSize, totalAmount, gridCount, gridType) {
        return this.generateSingleGridWithMode(initialPrice, 'percentage', gridSize, 0, totalAmount, gridCount, gridType);
    }

    /**
     * 模拟价格波动和交易
     */
    simulateTrading(params, gridData, strategy) {
        const { initialPrice, maxDecline } = params;
        const priceHistory = [initialPrice];
        const profitHistory = [0];

        let currentPrice = initialPrice;
        let totalProfit = 0;
        let completedTrades = 0;
        let retainedProfits = 0;

        // 模拟价格下跌到最大跌幅
        const minPrice = initialPrice * (1 - maxDecline / 100);
        const steps = 100;
        
        for (let i = 1; i <= steps; i++) {
            // 模拟价格波动
            const declineProgress = i / steps;
            const basePrice = initialPrice * (1 - maxDecline / 100 * declineProgress);
            const randomFactor = 0.95 + Math.random() * 0.1;
            currentPrice = basePrice * randomFactor;

            priceHistory.push(currentPrice);

            // 根据策略检查交易触发
            let newTrades;
            if (strategy === 'profit-retention') {
                newTrades = this.checkProfitRetentionTriggers(currentPrice, gridData, completedTrades, params.profitRetentionRate);
            } else if (strategy === 'progressive-betting') {
                newTrades = this.checkProgressiveBettingTriggers(currentPrice, gridData, completedTrades);
            } else if (strategy === 'multi-grid') {
                newTrades = this.checkMultiGridTriggers(currentPrice, gridData, completedTrades);
            }

            totalProfit += newTrades.profit;
            retainedProfits += newTrades.retainedProfit || 0;
            completedTrades += newTrades.count;

            profitHistory.push(totalProfit);
        }

        return { 
            priceHistory, 
            profitHistory, 
            completedTrades, 
            totalProfit, 
            retainedProfits 
        };
    }

    /**
     * 检查留利润策略的交易触发
     */
    checkProfitRetentionTriggers(currentPrice, gridData, completedTrades, profitRetentionRate) {
        let profit = 0;
        let retainedProfit = 0;
        let count = 0;

        for (let i = completedTrades; i < gridData.length; i++) {
            const grid = gridData[i];
            const buyPrice = parseFloat(grid.buyPrice);
            const sellPrice = parseFloat(grid.sellPrice);

            if (currentPrice <= buyPrice) {
                const baseReturn = parseFloat(grid.expectedReturn);
                const retained = baseReturn * (profitRetentionRate / 100);
                const actual = baseReturn - retained;
                
                profit += actual;
                retainedProfit += retained;
                count++;
            }
        }

        return { profit, retainedProfit, count };
    }

    /**
     * 检查逐格加码策略的交易触发
     */
    checkProgressiveBettingTriggers(currentPrice, gridData, completedTrades) {
        let profit = 0;
        let count = 0;

        for (let i = completedTrades; i < gridData.length; i++) {
            const grid = gridData[i];
            const buyPrice = parseFloat(grid.buyPrice);
            const sellPrice = parseFloat(grid.sellPrice);

            if (currentPrice <= buyPrice) {
                const tradeProfit = parseFloat(grid.expectedReturn);
                profit += tradeProfit;
                count++;
            }
        }

        return { profit, count };
    }

    /**
     * 检查一网打尽策略的交易触发
     */
    checkMultiGridTriggers(currentPrice, gridData, completedTrades) {
        let profit = 0;
        let count = 0;

        // 检查所有网格系统
        Object.values(gridData).forEach(grid => {
            grid.forEach((item, index) => {
                if (index >= completedTrades) {
                    const buyPrice = parseFloat(item.buyPrice);
                    const sellPrice = parseFloat(item.sellPrice);

                    if (currentPrice <= buyPrice) {
                        const tradeProfit = parseFloat(item.expectedReturn);
                        profit += tradeProfit;
                        count++;
                    }
                }
            });
        });

        return { profit, count };
    }

    /**
     * 计算统计指标
     */
    calculateStatistics(gridData, simulationResult, strategy) {
        const { totalProfit, completedTrades, retainedProfits } = simulationResult;
        const totalAmount = this.getTotalAmount(gridData, strategy);
        const totalReturnRate = (totalProfit / totalAmount) * 100;
        const avgReturnPerTrade = completedTrades > 0 ? totalProfit / completedTrades : 0;
        const maxDrawdown = this.calculateMaxDrawdown(simulationResult.profitHistory);

        const stats = {
            totalProfit: totalProfit.toFixed(2),
            totalReturnRate: totalReturnRate.toFixed(2),
            completedTrades,
            avgReturnPerTrade: avgReturnPerTrade.toFixed(2),
            maxDrawdown: maxDrawdown.toFixed(2),
            totalAmount: totalAmount.toFixed(2)
        };

        if (strategy === 'profit-retention') {
            stats.retainedProfits = retainedProfits.toFixed(2);
        }

        return stats;
    }

    /**
     * 获取总投入金额
     */
    getTotalAmount(gridData, strategy) {
        if (strategy === 'multi-grid') {
            return Object.values(gridData).reduce((total, grid) => {
                return total + grid.reduce((sum, item) => sum + parseFloat(item.amount), 0);
            }, 0);
        } else {
            return gridData.reduce((sum, item) => sum + parseFloat(item.amount), 0);
        }
    }

    /**
     * 计算最大回撤
     */
    calculateMaxDrawdown(profitHistory) {
        let maxDrawdown = 0;
        let peak = 0;

        for (const profit of profitHistory) {
            if (profit > peak) {
                peak = profit;
            }
            const drawdown = peak - profit;
            if (drawdown > maxDrawdown) {
                maxDrawdown = drawdown;
            }
        }

        return maxDrawdown;
    }

    /**
     * 更新统计卡片
     */
    updateStatsGrid(stats, strategy) {
        const statsGrid = document.getElementById('statsGrid');
        let statsHTML = `
            <div class="stat-card">
                <h3>总收益</h3>
                <div class="value ${stats.totalProfit >= 0 ? 'profit' : 'loss'}">
                    ¥${stats.totalProfit}
                </div>
            </div>
            <div class="stat-card">
                <h3>总收益率</h3>
                <div class="value ${stats.totalReturnRate >= 0 ? 'profit' : 'loss'}">
                    ${stats.totalReturnRate}%
                </div>
            </div>
            <div class="stat-card">
                <h3>完成交易数</h3>
                <div class="value">${stats.completedTrades}</div>
            </div>
            <div class="stat-card">
                <h3>平均每笔收益</h3>
                <div class="value ${stats.avgReturnPerTrade >= 0 ? 'profit' : 'loss'}">
                    ¥${stats.avgReturnPerTrade}
                </div>
            </div>
            <div class="stat-card">
                <h3>最大回撤</h3>
                <div class="value loss">¥${stats.maxDrawdown}</div>
            </div>
            <div class="stat-card">
                <h3>总投入</h3>
                <div class="value">¥${stats.totalAmount}</div>
            </div>
        `;

        if (strategy === 'profit-retention' && stats.retainedProfits) {
            statsHTML += `
                <div class="stat-card">
                    <h3>保留利润</h3>
                    <div class="value profit">¥${stats.retainedProfits}</div>
                </div>
            `;
        }

        statsGrid.innerHTML = statsHTML;
    }

    /**
     * 更新网格表格
     */
    updateGridTable(gridData, strategy) {
        const tbody = document.getElementById('gridTableBody');
        
        if (strategy === 'multi-grid') {
            // 多网格显示
            let tableHTML = '';
            Object.entries(gridData).forEach(([type, grid]) => {
                tableHTML += `<tr><td colspan="6" style="background: #e9ecef; font-weight: bold;">${type}网格</td></tr>`;
                grid.forEach(item => {
                    tableHTML += `
                        <tr>
                            <td>${item.level}</td>
                            <td>${item.buyPrice}</td>
                            <td>${item.sellPrice}</td>
                            <td>¥${item.amount}</td>
                            <td class="${parseFloat(item.expectedReturn) >= 0 ? 'profit' : 'loss'}">
                                ¥${item.expectedReturn}
                            </td>
                            <td class="${parseFloat(item.returnRate) >= 0 ? 'profit' : 'loss'}">
                                ${item.returnRate}%
                            </td>
                        </tr>
                    `;
                });
            });
            tbody.innerHTML = tableHTML;
        } else {
            // 单网格显示
            tbody.innerHTML = gridData.map(grid => `
                <tr>
                    <td>${grid.level}</td>
                    <td>${grid.buyPrice}</td>
                    <td>${grid.sellPrice}</td>
                    <td>¥${grid.amount}</td>
                    <td class="${parseFloat(grid.expectedReturn) >= 0 ? 'profit' : 'loss'}">
                        ¥${grid.expectedReturn}
                    </td>
                    <td class="${parseFloat(grid.returnRate) >= 0 ? 'profit' : 'loss'}">
                        ${grid.returnRate}%
                    </td>
                </tr>
            `).join('');
        }
    }

    /**
     * 更新图表
     */
    updateCharts(simulationResult) {
        const { priceHistory, profitHistory } = simulationResult;
        const labels = priceHistory.map((_, index) => `第${index + 1}天`);

        this.charts.price.data.labels = labels;
        this.charts.price.data.datasets[0].data = priceHistory;
        this.charts.price.update();

        this.charts.profit.data.labels = labels;
        this.charts.profit.data.datasets[0].data = profitHistory;
        this.charts.profit.update();
    }

    /**
     * 显示结果摘要
     */
    showResultSummary(params, stats, strategy) {
        let summary = `压力测试完成！\n\n`;
        
        if (strategy === 'profit-retention') {
            summary += `策略: 2.1 留利润\n`;
            summary += `利润保留比例: ${params.profitRetentionRate}%\n`;
        } else if (strategy === 'progressive-betting') {
            summary += `策略: 2.2 逐格加码\n`;
            summary += `每格增加比例: ${params.increaseRate}%\n`;
        } else if (strategy === 'multi-grid') {
            summary += `策略: 2.3 一网打尽\n`;
            summary += `小网: ${params.smallGridRatio}%, 中网: ${params.mediumGridRatio}%, 大网: ${params.largeGridRatio}%\n`;
        }

        summary += `\n测试结果:\n`;
        summary += `- 总收益: ¥${stats.totalProfit}\n`;
        summary += `- 总收益率: ${stats.totalReturnRate}%\n`;
        summary += `- 完成交易: ${stats.completedTrades}笔\n`;
        summary += `- 最大回撤: ¥${stats.maxDrawdown}\n`;

        if (stats.retainedProfits) {
            summary += `- 保留利润: ¥${stats.retainedProfits}\n`;
        }

        alert(summary);
    }
}

// 全局实例
const gridSystem2 = new GridTradingSystem2();

// 2.1 留利润策略测试
function runProfitRetentionTest() {
    const gridMode = document.getElementById('gridMode1').value;
    const params = {
        etfName: document.getElementById('etfName1').value,
        initialPrice: parseFloat(document.getElementById('initialPrice1').value),
        gridMode: gridMode,
        gridSize: parseFloat(document.getElementById('gridSize1').value),
        gridStep: parseFloat(document.getElementById('gridStep1').value),
        totalAmount: parseFloat(document.getElementById('totalAmount1').value),
        profitRetentionRate: parseFloat(document.getElementById('profitRetentionRate').value),
        maxDecline: parseFloat(document.getElementById('maxDecline1').value),
        gridCount: parseInt(document.getElementById('gridCount1').value)
    };

    const gridData = gridSystem2.generateProfitRetentionGrid(params);
    gridSystem2.updateGridTable(gridData, 'profit-retention');

    const simulationResult = gridSystem2.simulateTrading(params, gridData, 'profit-retention');
    const stats = gridSystem2.calculateStatistics(gridData, simulationResult, 'profit-retention');
    
    gridSystem2.updateStatsGrid(stats, 'profit-retention');
    gridSystem2.updateCharts(simulationResult);
    gridSystem2.showResultSummary(params, stats, 'profit-retention');
}

// 2.2 逐格加码策略测试
function runProgressiveBettingTest() {
    const gridMode = document.getElementById('gridMode2').value;
    const params = {
        etfName: document.getElementById('etfName2').value,
        initialPrice: parseFloat(document.getElementById('initialPrice2').value),
        gridMode: gridMode,
        gridSize: parseFloat(document.getElementById('gridSize2').value),
        gridStep: parseFloat(document.getElementById('gridStep2').value),
        baseAmount: parseFloat(document.getElementById('baseAmount2').value),
        increaseRate: parseFloat(document.getElementById('increaseRate').value),
        startFromGrid: parseInt(document.getElementById('startFromGrid').value),
        maxDecline: parseFloat(document.getElementById('maxDecline2').value),
        gridCount: parseInt(document.getElementById('gridCount2').value)
    };

    const gridData = gridSystem2.generateProgressiveBettingGrid(params);
    gridSystem2.updateGridTable(gridData, 'progressive-betting');

    const simulationResult = gridSystem2.simulateTrading(params, gridData, 'progressive-betting');
    const stats = gridSystem2.calculateStatistics(gridData, simulationResult, 'progressive-betting');
    
    gridSystem2.updateStatsGrid(stats, 'progressive-betting');
    gridSystem2.updateCharts(simulationResult);
    gridSystem2.showResultSummary(params, stats, 'progressive-betting');
}

// 2.3 一网打尽策略测试
function runMultiGridTest() {
    const gridMode = document.getElementById('gridMode3').value;
    const params = {
        etfName: document.getElementById('etfName3').value,
        initialPrice: parseFloat(document.getElementById('initialPrice3').value),
        gridMode: gridMode,
        totalAmount: parseFloat(document.getElementById('totalAmount3').value),
        smallGridRatio: parseFloat(document.getElementById('smallGridRatio').value),
        mediumGridRatio: parseFloat(document.getElementById('mediumGridRatio').value),
        largeGridRatio: parseFloat(document.getElementById('largeGridRatio').value),
        smallGridLayers: parseInt(document.getElementById('smallGridLayers').value),
        mediumGridLayers: parseInt(document.getElementById('mediumGridLayers').value),
        largeGridLayers: parseInt(document.getElementById('largeGridLayers').value),
        smallGridSize: parseFloat(document.getElementById('smallGridSize').value),
        mediumGridSize: parseFloat(document.getElementById('mediumGridSize').value),
        largeGridSize: parseFloat(document.getElementById('largeGridSize').value),
        smallGridStep: parseFloat(document.getElementById('smallGridStep').value),
        mediumGridStep: parseFloat(document.getElementById('mediumGridStep').value),
        largeGridStep: parseFloat(document.getElementById('largeGridStep').value),
        maxDecline: parseFloat(document.getElementById('maxDecline3').value)
    };

    const gridData = gridSystem2.generateMultiGridData(params);
    gridSystem2.updateGridTable(gridData, 'multi-grid');

    const simulationResult = gridSystem2.simulateTrading(params, gridData, 'multi-grid');
    const stats = gridSystem2.calculateStatistics(gridData, simulationResult, 'multi-grid');
    
    gridSystem2.updateStatsGrid(stats, 'multi-grid');
    gridSystem2.updateCharts(simulationResult);
    gridSystem2.showResultSummary(params, stats, 'multi-grid');
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('ETF网格交易2.0系统已加载');
});